package  org.baicaix.utils{
	import flash.events.Event;
	import flash.display.DisplayObject;

	/**
	 * 用于自动布局的工具类
	 * @author dengyang
	 * @date 2010-9-8
	 */
	public class LayoutUtil {

		public static function centerInStage(target : DisplayObject) : void {
			actionWhenAddToStage(target, center);
			
			function center() : void {
				target.x = (target.stage.stageWidth - target.width) / 2;
				target.y = (target.stage.stageHeight - target.height) / 2;
			}
		}

		public static function actionWhenAddToStage(target : DisplayObject, callback : Function) : void {
			if(target.stage) {
				callback();
			} else {
				target.addEventListener(Event.ADDED_TO_STAGE, addToStageHandler);
			}
			function addToStageHandler(event : Event = null) : void {
				target.removeEventListener(Event.ADDED_TO_STAGE, addToStageHandler);
				callback();
			}
		}

		public static function actionWhenAddToStageMultTimes(target : DisplayObject, callback : Function) : void {
			if(target.stage) {
				callback();
			} else {
				target.addEventListener(Event.ADDED_TO_STAGE, addToStageHandler);
			}
			function addToStageHandler(event : Event = null) : void {
				callback();
			}
		}

		public static function actionWhenRemoveFromStage(target : DisplayObject, callback : Function) : void {
			if(!target.stage) {
				callback();
			} else {
				target.addEventListener(Event.REMOVED_FROM_STAGE, removeFromStageHandler);
			}
			function removeFromStageHandler(event : Event = null) : void {
				target.removeEventListener(Event.REMOVED_FROM_STAGE, removeFromStageHandler);
				callback();
			}
		}

		public static function removeFromParent(target : DisplayObject) : void {
			if(target && target.parent) {
				target.parent.removeChild(target);
			}
		}
	}
}
